<?php

function win_observation_simple_search() {
  $path = drupal_get_path('module','win_observation');
  drupal_add_js($path . '/js/external/jquery-1.3.2.js');
  drupal_add_js($path . '/js/external/jquery.dataTables.js');
  drupal_add_js($path . '/js/search_results_page.js');

  drupal_add_css($path . '/css/jquery.datatable/css/demo_table.css');

  return drupal_get_form('win_observation_simple_search_form');
}

function win_observation_simple_search_form($form_state) {
  $form = array();

  ahah_helper_register($form, $form_state);

  if (!isset($form_state['clicked_button']['#post']['wo_search'])) {
    $search_string = '';
  }
  else {
    $search_string =  $form_state['clicked_button']['#post']['wo_search'];
  }

  $form['wo_simple_search_ui'] = array(
    '#prefix' => '<center><div class="container-inline">',
    '#suffix' => '</div></center>',
  );

  $form['wo_simple_search_ui']['info'] = array(
    '#value' => t('<p><em>To view a list of all the validated observations click on <a href="'.base_path().'observation/search/browse">Browse Observations</a></em></p>')
  );

  $form['wo_simple_search_ui']['wo_search'] = array(
    '#title' => '',
    '#type' => 'textfield',
    '#size' => 30,
    '#required' => TRUE,
    '#value' => $search_string,
  );

  $form['wo_simple_search_ui']['wo_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
    '#ahah' => array(
      'event'   => 'change',
      // This is the "magical path". Note that the parameter is an array of
      // the parents of the form item of the wrapper div!
      'path'    => ahah_helper_path(array('wo_simple_search_result')),
      'wrapper' => 'wo-simple-search-result-wrapper',
    ),
  );

  if ($form_state['submitted']) {
    $search_result = win_observation_perform_simple_search($search_string);
  }
  else {
    $search_result = '';
  }

  $form['wo_simple_search_result'] = array(
    '#prefix' => '<div id="wo-simple-search-result-wrapper">',
    '#suffix' => '</div>',
    '#tree'   => TRUE, // Don't forget to set #tree!
    '#value' => $search_result,
  );

  return $form;
}

function win_observation_perform_simple_search($search_string) {
  if (empty($search_string)) {
    display_message('error', 'Please enter some text in the search box.');
    return '';
  }

  $search_string = strtolower($search_string);
  $esc_str = _escape_accidental_placeholders_from_Drupal(db_escape_string($search_string));

  $cols = array();
  $db_name = get_current_db_name();
  $query = "select column_name from information_schema.columns where table_catalog = '{$db_name}' and table_name = 'win_observation_textual_data_view' and data_type = 'character varying'";
  $result = db_query($query);
  if (!$result) {
    display_message('error', 'Error talking to database.');
    return '';
  }
  else {
    while ($obj = db_fetch_object($result)) {
      $cols[] = $obj->column_name;
    }
  }

  $query_where = array();
  foreach ($cols as $col) {
    $query_where[] = "lower({$col}) like '%" . $esc_str . "%'";
  }

  $oids = array();

  $tablename = 'win_observation_textual_data_view';
  $id_col = 'id';
  $sql_filter_unvalidated = " and {$id_col} in (select observation_id from win_validation where status = 1)";
  $query = "select {$id_col} from {$tablename} where (" . implode(' or ', $query_where) . ") {$sql_filter_unvalidated};";
  $result = db_query($query);
  if (!$result) {
    display_message('error', 'Error talking to database.');
    return '';
  }
  else {
    while ($obj = db_fetch_object($result)) {
      $oids[] = $obj->id;
    }
  }
  
  $cols = array();
  $cols[] = 'common_name';
  $cols[] = 'cn_language';
  $cols[] = 'region';
  $cols[] = 'gender';
  $cols[] = 'lifestage';

  $query_where = array();
  foreach ($cols as $col) {
    $query_where[] = "lower({$col}) like '%" . $esc_str . "%'";
  }

  $tablename = 'win_common_names';
  $id_col = 'observation_id';

  $sql_filter_unvalidated = " and {$id_col} in (select observation_id from win_validation where status = 1)";
  $query = "select {$id_col} from {$tablename} where (" . implode(' or ', $query_where) . ") {$sql_filter_unvalidated};";
  $result = db_query($query);
  if (!$result) {
    display_message('error', 'Error talking to database.');
    return '';
  } else {
    while ($obj = db_fetch_object($result)) {
      $oids[] = $obj->{$id_col};
    }
  }
  
  $oids = array_unique($oids);
  
  $observations = get_observation_info_for_search_results($oids);
  $html = show_search_results($observations);
  $html .= show_download_UI();
  return $html;
}

function show_download_UI() {
  $base_path = base_path();
  
  $html = <<<EOT
  <div style=" text-align: left;">
    <div style="font-weight: bold; font-size: 15px;">Download search results</div>
    <div style="width:100%; text-align: center;">
      We are currently working on this feature. This feature will allow you to download the search results in XLS and CSV formats.
      <img alt="Work in Progress" src="{$base_path}sites/default/files/work_in_progress.png" />
    </div>
  </div>
EOT;
  
  return $html;
}